package cn.aiyuan.domain;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wy
 * @since 2021/11/4
 */
@Data
public class Temp {

    private String name;

    private String age;

    private int size;

    private List<Item> data;


    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Item {

        private String date;

        private int num;

    }


    public static void main(String[] args) {

        Temp temp = new Temp();
        temp.setData(ListUtil.of(new Item("2021", 99), new Item("2022", 1000)));
        temp.setSize(2);
        temp.setName("1");
        temp.setAge("1");

        Temp temp2 = new Temp();
        temp2.setData(ListUtil.of(new Item("2021", 199), new Item("2022", 199), new Item("2023", 199)));
        temp2.setName("2");
        temp2.setAge("2");
        temp2.setSize(3);


        ArrayList<Temp> data = new ArrayList<>();


        data.add(temp);
        data.add(temp2);

        //999999999999
        Temp first = data.stream().max(Comparator.comparing(Temp::getSize)).orElse(new Temp());

        Map<String, Integer> integerMap = first.getData().stream().collect(Collectors.toMap(Item::getDate, Item::getNum, (k1, k2) -> k1, LinkedHashMap::new));

        List<Map<String, Object>> rows = new ArrayList<>();

        for (Temp datum : data) {
            HashMap<String, Object> row = new LinkedHashMap<>();
            String name = datum.getName();
            String age = datum.getAge();
            row.put("name", name);
            row.put("age", age);

            Map<String, Integer> daMap = datum.getData().stream().collect(Collectors.toMap(Item::getDate, Item::getNum));
            integerMap.forEach((key, val) -> {
                Integer integer = daMap.get(key);
                if (Objects.isNull(integer)) {
                    row.put(key, 0);
                } else {
                    row.put(key, integer);
                }

            });

            rows.add(row);
        }


        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter("C:\\Users\\Administrator\\Desktop\\writeMapTest.xlsx");
        // 一次性写出内容，使用默认样式，强制输出标题
        //writer.merge(row1.size() - 1, "一班成绩单");
        writer.write(rows, true);
        // 关闭writer，释放内存
        writer.close();


    }
}
